<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from './dept.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import {
    getDeptList,
    createDept,
    updateDept,
    checkInvalidDept,
    searchDept,
  } from '/@/api/sys/dept';
  export default defineComponent({
    name: 'DeptModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');
      const { createMessage } = useMessage();
      const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
        labelWidth: 100,
        schemas: formSchema,
        showActionButtonGroup: false,
      });

      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });

        isUpdate.value = !!data?.isUpdate;

        if (unref(isUpdate)) {
          rowId.value = data.record.id;
          const records = await searchDept(rowId.value);
          setFieldsValue({
            ...records,
          });
        }
        const treeData = await getDeptList();
        updateSchema([
          {
            field: 'parentId',
            componentProps: { treeData },
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增部门' : '编辑部门'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });

          var success;
          if (unref(isUpdate)) {
            values.id = unref(rowId);
            var relationCount = checkInvalidDept(values);
            relationCount.then(async (rc) => {
              if (rc > 0) {
                const { createConfirm } = useMessage();
                let msg = '';

                if (values.status === 1) {
                  msg = '启用当前部门将同时启用其所有被停用的上级部门，是否继续？';
                } else {
                  msg = '停用当前部门将同时停用其所有被启用的下级部门，是否继续？';
                }
                createConfirm({
                  iconType: 'warning',
                  title: '警告',
                  content: () => msg,
                  onOk: () => {
                    success = updateDept(values);
                    //成功之后才能关闭界面
                    success.then(() => {
                      createMessage.success('操作成功');
                      closeModal();
                      emit('success');
                    });
                  },
                });
              } else {
                success = updateDept(values);
                //成功之后才能关闭界面
                success.then(() => {
                  createMessage.success('操作成功');
                  closeModal();
                  emit('success');
                });
              }
            });
          } else {
            success = createDept(values);
          }

          //成功之后才能关闭界面
          success.then(() => {
            createMessage.success('操作成功');
            closeModal();
            emit('success');
          });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit };
    },
  });
</script>
